﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using LitJson;
using System.Collections.Generic;
using System.Web.Security;
using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Text;
using System.Web.Security;
using System.Xml;

namespace msBsc.WebUi
{
    public class WxApiHandler : IHttpHandler, IRequiresSessionState
    {
        public WxApiHandler()
        {
        }
         

        public void ProcessRequest(HttpContext context)
        {
            if (!Auth())
            {
                return;
            }

            string echoString = HttpContext.Current.Request.QueryString["echoStr"];
            if (!string.IsNullOrEmpty(echoString))
            {
                HttpContext.Current.Response.Write(echoString);
                HttpContext.Current.Response.End();
            }



            string postString = string.Empty;
            if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
            {
                using (Stream stream = HttpContext.Current.Request.InputStream)
                {
                    Byte[] postBytes = new Byte[stream.Length];
                    stream.Read(postBytes, 0, (Int32)stream.Length);
                    postString = Encoding.UTF8.GetString(postBytes);
                    msBsc.AppLogic.Cfg.ApplicationLog.WriteActivityLog("微信测试：" + postString);
                    Handle(postString);
                }
            }
            //doPageAjax(context);
        }

        /// <summary>
        /// 处理信息并应答
        /// </summary>
        private void Handle(string postStr)
        {
            //if (!Auth())
            //{
            //    return;
            //}

            //string echoString = HttpContext.Current.Request.QueryString["echoStr"];
            //if (!string.IsNullOrEmpty(echoString))
            //{
            //    HttpContext.Current.Response.Write(echoString);
            //    HttpContext.Current.Response.End();
            //    return;
            //}


            messageHelp help = new messageHelp();
            string responseContent = help.ReturnMessage(postStr);

            HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; 
            HttpContext.Current.Response.Write(responseContent);
        }


         
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// 成为开发者的第一步，验证并相应服务器的数据
        /// </summary>
        private bool Auth()
        {
            string token = msBsc.SvRef.SysConst.WeixinToken;// get["WeixinToken"];//从配置文件获取Token
            if (string.IsNullOrEmpty(token))
            {
               return false;
            }

            string signature = HttpContext.Current.Request.QueryString["signature"];
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = HttpContext.Current.Request.QueryString["nonce"];

            if (CheckSignature(token, signature, timestamp, nonce))
            {
                return true;
                //if (!string.IsNullOrEmpty(echoString))
                //{
                //    HttpContext.Current.Response.Write(echoString);
                //    HttpContext.Current.Response.End();
                //}
            }
            return false;
        }

        /// <summary>
        /// 验证微信签名
        /// </summary>
        public bool CheckSignature(string token, string signature, string timestamp, string nonce)
        {
            string[] ArrTmp = { token, timestamp, nonce };

            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);

            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();

            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


    }
}